<script setup>
import {
    Edit, Delete, Link, Download, Check, Close
} from '@element-plus/icons-vue'
import axios from 'axios';
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import {
    addstaffservice, deletestaffservice, updatestaffservice, getAllservice, findByClueservice
} from '@/api/chance.js'

import {
    getallclientservice, getpartkeymanservice, getKeyManByID
} from '@/api/client.js'


import {
    getallareaservice, getalluserservice, getallareamasterservice
} from '@/api/book.js'
import {
    userInfoService
} from '@/api/user.js'


import {
    addtraceuserservice
} from '@/api/traceuser.js'

//控制添加分类弹窗
const dialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型

//定义变量，控制标题
const title = ref('')

//交通路线列表数据模型
const majors = ref([
    { id: 11 }, { id: 23 }
])
const keymans = ref([])
const formref = ref(null); //表单校验
//与后端交互的json数据
const pathmodel = ref({
    chancename: null,
    projectname: null,
    phase: null,
    areaname: null,
    budget: null,
    areas: null,
    chancedatetime: null,
    comment: null,
    keymen: null,
    clientcompanyid: null,
    stock: null,
    clue: null
})


const isFormDisabled = ref(false);
const isKeymanSectionDisabled = ref(false);
// 监听 phase 的变化
watch(() => pathmodel.value.phase, (newVal) => {
    isFormDisabled.value = (newVal !== '未提交' && title.value === '销售机会编辑');
    isKeymanSectionDisabled.value = (newVal !== '未提交' && title.value === '销售机会编辑');
});


const temp = ref({
    keyman: []
})





const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: '',
    findType: null
})

const findmodelkey = ref({
    clientcompanyid: null,
    str: '',
})
const keymanOptions = ref({

})

const getAllKeyman = async () => {
    let result = await getpartkeymanservice(findmodelkey.value);

    //console.log("客户是" + findmodelkey.value.clientcompanyid);
    //console.log("关键人物数据是" + JSON.stringify(result.data));
    keymanOptions.value = result.data;

}


const clientcompanyOptions = ref({

})

const getAllClient = async () => {
    let result = await getallclientservice();

    //console.log("客户数据是" + JSON.stringify(result.data));
    clientcompanyOptions.value = result.data;

}

const handleClientChange = (clientId) => {
    temp.value = {};
    // 找到对应的 item 对象
    const selectedItem = clientcompanyOptions.value.find(item => item.id === clientId);
    if (selectedItem) {
        findmodelkey.value.clientcompanyid = pathmodel.value.clientcompanyid;
        pathmodel.value.areaname = selectedItem.pet;
        getAllKeyman();
    }
};


const areasOptions = ref({

})


const getAllArea = async () => {
    let result = await getallareaservice();

    //console.log("片区数据是" + JSON.stringify(result.data));
    areasOptions.value = result.data;

}

const clueOptions = ref({

})



const getAllUser = async () => {
    let result = await getalluserservice();

    // console.log("员工数据是" + JSON.stringify(result.data));
    clueOptions.value = result.data;

}

const username = ref();

const getUser = async () => {
    let userresult = await userInfoService();
    userid = userresult.data.id;
    username_login = userresult.data.name;
    username.value = userresult.data.name;
    console.log("userid = " + userresult.data.id);
}

const findmodel2 = ref({
    pageNum: 1,
    pageSize: 10086,
    str: ''
})
const areamasters = ref([])

const getareamasters = async () => {

    let result2 = await getallareamasterservice(findmodel2.value)


    areamasters.value = result2.data.items;

}

const stafflist = async () => {
    let userresult2 = await userInfoService();
    findmodel.value.findType = userresult2.data.id;
    let result = await findByClueservice(findmodel.value);






    total.value = result.data.total;
    majors.value = result.data.items;
    console.log("销售机会信息:" + JSON.stringify(majors.value));
    getAllClient();
    getAllArea();
    getAllUser();
    getAllKeyman();
    getUser();
    getareamasters();


    // console.log("majors.value = " +JSON.stringify(majors.value))
}
stafflist();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    stafflist();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    stafflist();
}
const cleardata = () => {
    findmodel.value.str = '';
    findmodel.value.pageNum = 1;
    stafflist();
}
//表单校验
const rules = {
    chancename: [
        { required: true, message: '请输入机会名称', trigger: 'blur' },
    ],
    projectname: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
    budget: [
        { required: true, message: '请输入预算', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value < 0) {
                    callback(new Error('预算不能为负数'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ],
    areas: [
        { required: true, message: '请选择片区', trigger: 'blur' },
    ],
    chancedatetime: [
        { required: true, message: '请选择销售机会日期', trigger: 'blur' },
    ],
    clientcompanyid: [
        { required: true, message: '请选择客户', trigger: 'blur' },
    ],
    stock: [
        { required: true, message: '请输入存货', trigger: 'blur' },
    ],
    clue: [
        { required: true, message: '请输线索来源', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入备注', trigger: 'blur' },
    ]
}

let username_login = '';

let userid = 0;

const add = () => {

    temp.value = {};

    keymanOptions.value = {};
    for (let key in pathmodel.value) {
        if (pathmodel.value.hasOwnProperty(key)) {
            pathmodel.value[key] = null;
        }
    }

    pathmodel.value.clue = userid;

    username.value = username_login;



    keymans.value = [];
    dialogVisible.value = true;
    title.value = '销售机会录入';
}

const areachanceModel = ref({
    chanceid: null,
    userid: null
})

const addstaff = async () => {
    // console.log(pathmodel.value);

    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let tempareas = pathmodel.value.areas.join(',');
            pathmodel.value.areas = tempareas;
            pathmodel.value.phase = '未提交';
            let result = await addstaffservice(pathmodel.value);


            if (result.code == 0) {
                ElMessage.success("添加成功")
                dialogVisible.value = false;
                stafflist();






            }
            else ElMessage.error(result.message ? result.message : '添加失败')

            stafflist();


        }
    });



}

const addKeyman = async () => {
    // console.log(temp.value.keyman);

    // 将现有的 keymen 字符串转换为数组
    let keymanIds = pathmodel.value.keymen ? pathmodel.value.keymen.split(',') : [];

    // 遍历 temp.value.keyman 数组，并添加不重复的 keyman
    temp.value.keyman.forEach(keymanId => {
        keymanId = String(keymanId); // 确保 keymanId 是字符串类型
        if (!keymanIds.includes(keymanId)) {
            // 如果 keymanId 不在数组中，则添加它
            keymanIds.push(keymanId);
        }
    });


    pathmodel.value.keymen = keymanIds.join(',');

    // console.log("pathmodel.value.keymen = " + pathmodel.value.keymen);

    loadKeyMans();
};
const delkeymans = async (row) => {
    console.log("row2数据是" + JSON.stringify(row));
    ElMessageBox.confirm(
        '你确认删除该关键人物吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            keymans.value = keymans.value.filter(keyman => keyman.id !== row.id);
            pathmodel.value.keymen = keymans.value.map(keyman => keyman.id).join(',');
            console.log("pathmodel.value.keymen" + JSON.stringify(pathmodel.value.keymen));

ElMessage.success('删除成功')

            stafflist();
        })




}

const loadKeyMans = async () => {
    // 将keymen字符串分割成ID数组
    keymans.value = [];

    // console.log("pathmodel.value.keymen" + pathmodel.value.keymen)
    if (pathmodel.value.keymen == '') {
        console.log("keymen为空，无需加载关键人物数据。");
        return; // 直接返回，不执行后续操作
    }
    else    {
    
            console.log("pathmodel.value.keymen = " + pathmodel.value.keymen)

    }
    const keymenStr = String(pathmodel.value.keymen);

    // 检查keymen字符串是否包含逗号，以确定如何分割字符串
    const keymanIds = keymenStr.includes(',')
        ? keymenStr.split(',').map(Number)
        : [Number(keymenStr)];





    // 遍历ID数组，并获取每个keyman
    for (const id of keymanIds) {
        try {
            const keyman = await getKeyManByID(id);

            //console.log("现在关键人物数据是" + JSON.stringify(keyman.data));
            // 将获取到的keyman添加到keymans数组中
            keymans.value.push(keyman.data);
        } catch (error) {
            console.error(`Error fetching keyman with ID ${id}:`, error);
            // 处理错误，例如可以添加一个错误标记到keymans数组中
        }
    }
};




const updatestaff = async () => {
    //console.log(pathmodel.value);

    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let tempareas = pathmodel.value.areas.join(',');
            pathmodel.value.areas = tempareas;

            //时间问题
            const date = new Date(pathmodel.value.chancedatetime);

            date.setHours(date.getHours() + 8);
            pathmodel.value.chancedatetime = date.toISOString();

            let result = await updatestaffservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("修改成功")
                dialogVisible.value = false;
                stafflist();
            }
            else ElMessage.error(result.message ? result.message : '修改失败')
        }
    });
}

//删除分类
const del = (row) => {

    ElMessageBox.confirm(
        '你确认删除该机会吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认

            let result = await deletestaffservice(row.chanceid)
            if (result.code != 0) ElMessage.error(result.message ? result.message : '删除失败')
            else ElMessage.success('删除成功')
            //再次调用getAllCategory，获取所有文章分类
            stafflist();
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const closeChance = async (row) => {

    ElMessageBox.confirm(
        '你确认关闭该机会吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            pathmodel.value.chancename = row.chancename;
            pathmodel.value.projectname = row.projectname;
            pathmodel.value.phase = "已关闭";
            pathmodel.value.areaname = row.areaname;
            pathmodel.value.budget = row.budget;
            pathmodel.value.areas = row.areas;

            const date = new Date(row.chancedatetime);

            date.setHours(date.getHours() + 8);
            pathmodel.value.chancedatetime = date.toISOString();;
            pathmodel.value.comment = row.comment;
            pathmodel.value.keymen = row.keymen;
            pathmodel.value.clientcompanyid = row.clientcompanyid;
            pathmodel.value.stock = row.stock;
            pathmodel.value.clue = row.clue;

            pathmodel.value.chanceid = row.chanceid;




            let result = await updatestaffservice(pathmodel.value);
            if (result.code != 0) ElMessage.error(result.message ? result.message : '删除失败')
            else ElMessage.success('关闭成功')
            //再次调用getAllCategory，获取所有文章分类
            stafflist();
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消关闭',
            })
        })


}

const submit = async (row) => {

    pathmodel.value.chancename = row.chancename;
    pathmodel.value.projectname = row.projectname;
    pathmodel.value.phase = "未分配";
    pathmodel.value.areaname = row.areaname;
    pathmodel.value.budget = row.budget;
    pathmodel.value.areas = row.areas;

    const date = new Date(row.chancedatetime);

    date.setHours(date.getHours() + 8);
    pathmodel.value.chancedatetime = date.toISOString();;
    pathmodel.value.comment = row.comment;
    pathmodel.value.keymen = row.keymen;
    pathmodel.value.clientcompanyid = row.clientcompanyid;
    pathmodel.value.stock = row.stock;
    pathmodel.value.clue = row.clue;

    pathmodel.value.chanceid = row.chanceid;




    let result = await updatestaffservice(pathmodel.value);
    if (result.code == 0) {
        ElMessage.success("提交成功")
        stafflist();
    }
    else ElMessage.error(result.message ? result.message : '提交失败')



    areachanceModel.value.chanceid = pathmodel.value.chanceid;
    let userresult3 = await userInfoService();
    const userAreaId = userresult3.data.areaid;

    // 筛选出匹配的areamasters
    const matchedAreaMasters = areamasters.value.filter(item => item.areaid === userAreaId);

    // 遍历匹配的areamasters并处理每个匹配项
    for (const item of matchedAreaMasters) {
        areachanceModel.value.userid = item.id; // 设置areachanceModel的userid为筛选出的item的id
        let result3 = await addtraceuserservice(areachanceModel.value); // 调用服务添加跟踪用户
        // 这里可以处理result3，例如检查是否成功等
    }



}

//展示编辑弹窗
const showDialog = (row) => {
    title.value = '销售机会编辑';
    dialogVisible.value = true;


    pathmodel.value.chancename = row.chancename;
    pathmodel.value.projectname = row.projectname;
    pathmodel.value.phase = row.phase;
    pathmodel.value.areaname = row.areaname;
    pathmodel.value.budget = row.budget;
    pathmodel.value.areas = row.areas;


    pathmodel.value.chancedatetime = new Date(row.chancedatetime).toISOString();
    pathmodel.value.comment = row.comment;
    pathmodel.value.keymen = row.keymen;
    pathmodel.value.clientcompanyid = row.clientcompanyid;
    pathmodel.value.stock = row.stock;
    pathmodel.value.clue = row.clue;

    username.value = row.user.name;

    console.log("username = " + username.value);
    findmodelkey.value.clientcompanyid = pathmodel.value.clientcompanyid;
    getAllKeyman();

    loadKeyMans();
    let areasArray = pathmodel.value.areas.split(',').map(Number);
    pathmodel.value.areas = areasArray;
    pathmodel.value.chanceid = row.chanceid;






}
const addorupdate = async () => {
    console.log(title.value);
    if (title.value == '销售机会录入') {
        addstaff();
    }
    else {
        updatestaff();
    }
}






</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>销售机会信息登记</span>
                <div class="extra">
                    <el-button type="primary" @click="add">新增机会</el-button>
                </div>
            </div>
        </template>

        <!-- 搜索表单 -->
        <el-form>
            <el-form-item label="查询条件:">
                <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                <el-button @click="cleardata">重置</el-button>

            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="majors" style="width: 100%">
            <el-table-column label="机会名称" prop="chancename"></el-table-column>
            <el-table-column label="销售机会主题" prop="projectname"></el-table-column>
            <el-table-column label="存货" prop="stock"></el-table-column>
            <el-table-column label="预算" prop="budget"></el-table-column>
            <el-table-column label="线索来源" prop="user.name"></el-table-column>
            <el-table-column label="销售机会日期" prop="chancedatetime"></el-table-column>
            <el-table-column label="接受状态" prop="phase" width="80"></el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="del(row)"
                        :disabled="row.phase !== '未提交'"></el-button>
                    <el-button :icon="Check" circle plain type="primary" @click="submit(row)"
                        :disabled="row.phase !== '未提交'"></el-button>


                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
            :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
            @size-change="onSizeChange" @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end" />


    </el-card>

    <!-- 添加分类弹窗 -->


    <el-dialog v-model="dialogVisible" :title="title" width="60%">
        <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="120px" style="padding-right: 30px"
            :disabled="isFormDisabled">
            <div class="basic-info-border max-width-box">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="机会名称" prop="chancename">
                            <el-input v-model="pathmodel.chancename"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="项目名称" prop="projectname">
                            <el-input v-model="pathmodel.projectname"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="11">
                        <el-form-item label="客户" prop="clientcompanyid">

                            <el-select v-model="pathmodel.clientcompanyid" placeholder="请选择客户" style="width: 100%;"
                                @change="handleClientChange">
                                <el-option v-for="item in clientcompanyOptions" :key="item.id"
                                    :label="item.clientcompanyname" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="阶段" prop="phase">
                            <el-input v-model="pathmodel.phase" disabled></el-input>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row>
                    <el-col :span="11">
                        <el-form-item label="行业" prop="areaname">
                            <el-input v-model="pathmodel.areaname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="预算" prop="budget">
                            <el-input v-model="pathmodel.budget"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="11">
                        <el-form-item label="片区" prop="areas">
                            <el-select v-model="pathmodel.areas" multiple placeholder="请选择片区" style="width: 100%;">
                                <el-option v-for="item in areasOptions" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>



                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="销售机会日期" prop="chancedatetime">
                            <el-date-picker v-model="pathmodel.chancedatetime" type="datetime" placeholder="选择日期时间 "
                                style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="11">
                        <el-form-item label="存货" prop="stock">
                            <el-input v-model="pathmodel.stock"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">

                        <el-form-item label="线索来源" prop="clue">
                            <el-input v-model="username" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>




                <el-form-item label="备注" prop="comment">
                    <el-input type="textarea" :rows="4" v-model="pathmodel.comment" style="width: 710px"></el-input>
                </el-form-item>
            </div>

        </el-form>


        <div class="basic-info-border2 max-width-box">


            <!-- 下拉框组件 -->

            <div style="margin-top: -10px;margin-left: 10px;">
                <el-select v-model="temp.keyman" multiple placeholder="请选择关键人物" style="width: auto; margin-right: 10px;">
                <el-option v-for="item in keymanOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <!-- 添加关键人物按钮 -->
            <el-button type="primary" @click="addKeyman" :disabled="isFormDisabled">添加关键人物</el-button>
            </div>
           
            <el-table :data="keymans" style="width: 100%">
                <el-table-column label="所属客户" prop="clientcompanyid"></el-table-column>
                <el-table-column label="联系人编码" prop="code"></el-table-column>
                <el-table-column label="联系人名称" prop="name"></el-table-column>
                <el-table-column label="称呼" prop="nickname"></el-table-column>
                <el-table-column label="职务" prop="zhiwu"></el-table-column>
                <el-table-column label="备注" prop="comment"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="{ row }">
                        <el-button :icon="Delete" circle plain type="danger" @click="delkeymans(row)"
                            :disabled="isFormDisabled"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>

        </div>









        <!-- 分页条 -->
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addorupdate" :disabled="isFormDisabled"> 确认 </el-button>
            </span>
        </template>

    </el-dialog>

</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}


.basic-info-container {
    display: flex; // 使用flex布局
    flex-wrap: wrap; // 允许元素换行
    margin-right: -10px; // 调整外边距以对齐
}

.basic-info-border,
.basic-info-border2 {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    position: relative;
    padding-top: 30px;
    margin-bottom: 20px; // 添加底部外边距
    width: 100%; // 设置宽度为100%，或者您可以设置一个固定的宽度
    box-sizing: border-box; // 确保padding和border包含在宽度内
}

.basic-info-border::before,
.basic-info-border2::before {
    content: "";
    position: absolute;
    top: -15px;
    left: 10px;
    background-color: #409EFF;
    color: white;
    padding: 5px;
    border-radius: 3px;
    font-weight: bold;
}

.basic-info-border::before {
    content: "基本信息";
}

.basic-info-border2::before {
    content: "客户关键人物信息";
}

// 如果需要，可以为两个框设置最大宽度
.max-width-box {
    max-width: 900px; // 或者您希望的任何宽度
}
</style>